// 统一的API响应处理
function handleApiResponse(response) {
	// 适配新的响应格式
	if (response.success !== undefined) {
		// 新格式：{ success: boolean, code: number, message: string, data: any }
		return {
			code: response.success ? 200 : (response.code || 400),
			success: response.success,
			message: response.message || '',
			data: response.data || null,
			errors: response.errors || null
		};
	} else if (response.state !== undefined) {
		// 兼容旧格式：{ state: boolean, message: string, data: any }
		return {
			code: response.state ? 200 : 400,
			success: response.state,
			message: response.message || '',
			data: response.data || null,
			errors: null
		};
	} else {
		// 直接返回原始响应
		return response;
	}
}

// 构建 Authorization 头：按照API文档要求的格式
function buildAuthHeader() {
	const authHeader = {};
	const token = uni.getStorageSync('token') || uni.getStorageSync('jwt') || '';
	let userId = '';

	try {
		// 修复：从缓存读取名为 'sender' 的字符串
		const senderInfoRaw = uni.getStorageSync('sender');
		
		// 修复：安全地解析JSON字符串
		const senderInfo = senderInfoRaw ? JSON.parse(senderInfoRaw) : null;

		// 修复：使用最可靠的方式检查 'id' 属性，兼容 id 为 0 的情况
		if (senderInfo && typeof senderInfo.id !== 'undefined' && senderInfo.id !== null) {
			userId = senderInfo.id;
		} else if (senderInfo && typeof senderInfo.Id !== 'undefined' && senderInfo.Id !== null) {
			// 兼容大写的 'Id'
			userId = senderInfo.Id;
		}
		
	} catch (e) {
		console.error('buildAuthHeader: 解析用户信息时出错:', e);
	}

	// 按照API文档要求的格式：{token}:{userId}
	if (token) {
		// 确保 userId 是一个字符串，即使它是数字 0
		authHeader['Authorization'] = `${token}:${String(userId)}`;
	}
	
	return authHeader;
}

// 统一错误处理
function handleApiError(error, defaultMessage = '操作失败') {
	console.error('API Error:', error);
	
	if (error.response) {
		const { code, message, errors } = error.response.data || {};
		
		let errorMessage = message || defaultMessage;
		
		switch (code) {
			case 400:
				errorMessage = `输入错误: ${message}`;
				if (errors) {
					console.error('详细错误:', errors);
				}
				break;
			case 401:
				errorMessage = '请先登录';
				// 清除过期token
				uni.removeStorageSync('token');
				uni.removeStorageSync('jwt');
				// 只有在非登录页面时才跳转到登录页
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				if (currentPage && !currentPage.route.includes('index/index')) {
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/index/index' });
					}, 1500);
				}
				break;
			case 403:
				errorMessage = '权限不足';
				break;
			case 404:
				errorMessage = '资源不存在';
				break;
			case 500:
				errorMessage = '服务器错误，请稍后重试';
				break;
			default:
				errorMessage = message || defaultMessage;
		}
		
		return Promise.reject(new Error(errorMessage));
	} else if (error.request) {
		return Promise.reject(new Error('网络错误，请检查网络连接'));
	} else {
		return Promise.reject(new Error(error.message || defaultMessage));
	}
}

// 重试请求工具
async function retryRequest(requestFn, maxRetries = 3) {
	for (let i = 0; i < maxRetries; i++) {
		try {
			return await requestFn();
		} catch (error) {
			if (i === maxRetries - 1) throw error;
			await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
		}
	}
}

module.exports = {
	/**
	 * POST请求
	 * @param {string} url 请求地址
	 * @param {Object} data 请求参数
	 * @param {string} header 请求头类型
	 * @param {boolean} isLoad 是否显示加载动画
	 */
	post: function(url, data, header, isLoad) {
		header = header || 'application/json';
		isLoad = isLoad !== false;
		
		if (isLoad) {
			uni.showLoading({ title: "请求中...", mask: true });
		}
		
		return new Promise((resolve, reject) => {
			const auth = buildAuthHeader();
			
			uni.request({
				url: url,
				data: data,
				method: "POST",
				header: {
					"Content-Type": header,
					...auth,
				},
				success: function(result) {
					if (isLoad) uni.hideLoading();
					
					try {
						const response = handleApiResponse(result.data);
						resolve(response);
					} catch (error) {
						reject(error);
					}
				},
				fail: function(error) {
					if (isLoad) uni.hideLoading();
					handleApiError(error).catch(reject);
				}
			});
		});
	},

	/**
	 * GET请求
	 * @param {string} url 请求地址
	 * @param {Object} data 请求参数
	 * @param {string} header 请求头类型
	 * @param {boolean} isLoad 是否显示加载动画
	 */
	get: function(url, data, header, isLoad) {
		header = header || 'application/json';
		isLoad = isLoad !== false;
		
		if (isLoad) {
			uni.showLoading({ title: "加载中...", mask: true });
		}
		
		return new Promise((resolve, reject) => {
			const auth = buildAuthHeader();
			
			uni.request({
				url: url,
				data: data,
				method: "GET",
				header: {
					"Content-Type": header,
					...auth,
				},
				success: function(result) {
					if (isLoad) uni.hideLoading();
					
					try {
						const response = handleApiResponse(result.data);
						resolve(response);
					} catch (error) {
						reject(error);
					}
				},
				fail: function(error) {
					if (isLoad) uni.hideLoading();
					handleApiError(error).catch(reject);
				}
			});
		});
	},

	/**
	 * DELETE请求
	 * @param {string} url 请求地址
	 * @param {Object} data 请求参数
	 * @param {boolean} isLoad 是否显示加载动画
	 */
	delete: function(url, data, isLoad) {
		isLoad = isLoad !== false;
		
		if (isLoad) {
			uni.showLoading({ title: "删除中...", mask: true });
		}
		
		return new Promise((resolve, reject) => {
			const auth = buildAuthHeader();
			
			uni.request({
				url: url,
				data: data,
				method: "DELETE",
				header: {
					"Content-Type": 'application/json',
					...auth,
				},
				success: function(result) {
					if (isLoad) uni.hideLoading();
					
					try {
						const response = handleApiResponse(result.data);
						resolve(response);
					} catch (error) {
						reject(error);
					}
				},
				fail: function(error) {
					if (isLoad) uni.hideLoading();
					handleApiError(error).catch(reject);
				}
			});
		});
	},

	// ==================== 认证相关API ====================

	/**
	 * 用户登录
	 * @param {string} apiUrl API基础地址
	 * @param {Object} credentials 登录凭据
	 */
	login: function(apiUrl, credentials) {
		return this.post(apiUrl + "/api/auth/login", credentials);
	},

	/**
	 * 用户注册
	 * @param {string} apiUrl API基础地址
	 * @param {Object} userData 注册数据
	 */
	register: function(apiUrl, userData) {
		return this.post(apiUrl + "/api/auth/register", userData);
	},

	/**
	 * 发送验证码
	 * @param {string} apiUrl API基础地址
	 * @param {string} email 邮箱地址
	 */
	sendVerificationCode: function(apiUrl, email) {
		return this.post(apiUrl + "/api/auth/send-code", { email });
	},

	/**
	 * 获取咨询列表
	 * @param {string} apiUrl API基础地址
	 * @param {Object} params 查询参数
	 */
	getConsultationList: function(apiUrl, params = {}) {
		// 根据API文档，这是GET请求，不需要分页参数
		console.log('调用咨询列表API:', apiUrl + `/api/consultation/list`);
		return this.get(apiUrl + `/api/consultation/list`);
	},

	// ==================== 咨询相关API ====================


	/**
	 * 获取咨询消息
	 * @param {string} apiUrl API基础地址
	 * @param {string|number} consultationId 咨询ID
	 * @param {Object} params 查询参数
	 */
	getConsultationMessages: function(apiUrl, consultationId, params = {}) {
		// 根据API文档，使用GET请求，传递id参数
		return this.get(apiUrl + `/api/consultation/messages?id=${consultationId}`);
	},

	/**
	 * 创建咨询
	 * @param {string} apiUrl API基础地址
	 * @param {Object} consultationData 咨询数据
	 */
	createConsultation: function(apiUrl, consultationData = {}) {
		return this.post(apiUrl + "/api/consultation/create", consultationData);
	},

	/**
	 * 发送咨询消息
	 * @param {string} apiUrl API基础地址
	 * @param {Object} messageData 消息数据
	 */
	sendConsultationMessage: function(apiUrl, messageData) {
		return this.post(apiUrl + "/api/consultation/message/send", messageData);
	},

	/**
	 * 标记消息为已读
	 * @param {string} apiUrl API基础地址
	 * @param {string|number} consultationId 咨询ID
	 */
	markConsultationRead: function(apiUrl, consultationId) {
		return this.post(apiUrl + "/api/consultation/message/read", { consultationId });
	},

	/**
	 * 删除咨询
	 * @param {string} apiUrl API基础地址
	 * @param {string|number} consultationId 咨询ID
	 */
	deleteConsultation: function(apiUrl, consultationId) {
		// 根据API文档，使用POST请求
		return this.post(apiUrl + "/api/consultation/delete", { id: consultationId });
	},

	// ==================== 文件上传API ====================

	/**
	 * 上传文件
	 * @param {string} apiUrl API基础地址
	 * @param {string} filePath 文件路径
	 * @param {string} fileType 文件类型 ('file' | 'image')
	 */
	uploadFile: function(apiUrl, filePath, fileType = 'file') {
		return new Promise((resolve, reject) => {
			const auth = buildAuthHeader();
			const endpoint = fileType === 'image' ? '/api/upload/image' : '/api/upload/file';
			const fieldName = fileType === 'image' ? 'image' : 'file';
			
			uni.showLoading({ title: '上传中...', mask: true });
			
			uni.uploadFile({
				url: apiUrl + endpoint,
				filePath: filePath,
				name: fieldName,
				header: {
					...auth
				},
				success: (uploadResult) => {
					uni.hideLoading();
					
					try {
						if (uploadResult.statusCode === 200) {
							const response = handleApiResponse(JSON.parse(uploadResult.data));
							resolve(response);
						} else {
							reject(new Error('上传失败'));
						}
					} catch (error) {
						reject(new Error('上传响应解析失败'));
					}
				},
				fail: (error) => {
					uni.hideLoading();
					handleApiError(error, '文件上传失败').catch(reject);
				}
			});
		});
	},

	/**
	 * 上传图片
	 * @param {string} apiUrl API基础地址
	 * @param {string} imagePath 图片路径
	 */
	uploadImage: function(apiUrl, imagePath) {
		return this.uploadFile(apiUrl, imagePath, 'image');
	},

	// ==================== 工具方法 ====================

	/**
	 * 验证邮箱格式
	 * @param {string} email 邮箱地址
	 */
	validateEmail: function(email) {
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		return emailRegex.test(email);
	},

	/**
	 * 验证密码强度
	 * @param {string} password 密码
	 */
	validatePassword: function(password) {
		const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{6,20}$/;
		return passwordRegex.test(password);
	},

	/**
	 * 验证用户名格式
	 * @param {string} username 用户名
	 */
	validateUsername: function(username) {
		const usernameRegex = /^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$/;
		return usernameRegex.test(username);
	},

	/**
	 * 验证文件大小和类型
	 * @param {Object} file 文件对象
	 * @param {boolean} isImage 是否为图片
	 */
	validateFile: function(file, isImage = false) {
		const MAX_IMAGE_SIZE = 5 * 1024 * 1024; // 5MB
		const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
		const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif'];
		const ALLOWED_FILE_TYPES = [
			'application/pdf',
			'application/msword',
			'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
			'text/plain'
		];
		
		const maxSize = isImage ? MAX_IMAGE_SIZE : MAX_FILE_SIZE;
		const allowedTypes = isImage ? ALLOWED_IMAGE_TYPES : ALLOWED_FILE_TYPES;
		
		if (file.size > maxSize) {
			throw new Error(`文件大小不能超过 ${maxSize / 1024 / 1024}MB`);
		}
		
		if (!allowedTypes.includes(file.type)) {
			throw new Error('不支持的文件类型');
		}
		
		return true;
	}
}